package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.huaweicloud.sdk.core.auth.AbstractCredentials;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;

import com.huaweicloud.sdk.core.region.Region;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 设备Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-31
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


//    //REGION_ID：如果是上海一，请填写"cn-east-3"；
//    如果是北京四，请填写"cn-north-4";
//    如果是华南广州，请填写"cn-south-1"
//    // ENDPOINT：请在控制台的"总览"界面的"平台接入地址"中查看“应用侧”的https接入地址。

    @Value("${iot.HUAWEICLOUD_SDK_AK}")
    private String ak;

    @Value("${iot.HUAWEICLOUD_SDK_SK}")
    private String sk;

    @Value("${iot.iotdaEndpoint}")
    private String iotdaEndpoint;

//    @Value("${iot.project_id}")
//    private String projectId;

    @Value("${iot.region}")
    private String region;

    /**
     * 查询产品的物模型功能定义
     *
     * @param deviceDto
     * @return
     */
    @Override
    public AjaxResult queryThingModelPublished(DeviceDto deviceDto) {
        ICredential auth = new BasicCredentials()
                .withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE).withAk(ak).withSk(sk);

        IoTDAClient client = IoTDAClient.newBuilder().withCredential(auth)
                .withRegion(new Region(region, iotdaEndpoint)).build();
        ListPropertiesRequest request = new ListPropertiesRequest();
        request.withDeviceId(deviceDto.getIotId());
        request.withServiceId("BasicService");

        ListPropertiesResponse response = client.listProperties(request);

        return AjaxResult.success(response.getResponse());

    }

    /**
     * 查询设备属性状态（查询物属性状态）
     *
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(String iotId) {
        ICredential auth = new BasicCredentials()
                .withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE).withAk(ak).withSk(sk);

        IoTDAClient client = IoTDAClient.newBuilder().withCredential(auth)
                .withRegion(new Region(region, iotdaEndpoint)).build();
        ListPropertiesRequest request = new ListPropertiesRequest();
        request.withDeviceId(iotId);
        request.withServiceId("BasicService");

        ListPropertiesResponse response = client.listProperties(request);

        return AjaxResult.success(response.getResponse());
    }

    /**
     * 查询设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceVo queryDeviceDetail(String iotId) {

        ICredential auth = new BasicCredentials()
                .withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE).withAk(ak).withSk(sk);

        IoTDAClient client = IoTDAClient.newBuilder()
                .withCredential(auth).withRegion(new Region("cn-east-3", iotdaEndpoint)).build();
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response;

        try {
            response = client.showDevice(request);

        } catch (Exception e) {
            throw new BaseException("IOT调用，查询设备详情失败");
        }
        //判断接口调通了
        if(response.getHttpStatusCode()==400){
            throw new BaseException("IOT调用失败");
        }

        //根据iotid查询数据库的设备
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        //第一次拷贝，只包含了数据库中的设备数据
        DeviceVo deviceVo = BeanUtil.toBean(device, DeviceVo.class);

        //第二次拷贝，包含了iot接口返回的设备数据
        deviceVo.setDeviceSecret(response.getAuthInfo().getSecret());
        deviceVo.setFirmwareVersion(response.getFwVersion());
        deviceVo.setStatus(response.getStatus());
        deviceVo.setGmtCreate(response.getCreateTime());

        //不改变deviceVo和前端的逻辑
        Integer NT = response.getNodeType()=="ENDPOINT"?1:0;
        deviceVo.setNodeType(NT);

        deviceVo.setRegion(region);

        return deviceVo;

    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //判断设备名称是否重复
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if(count > 0){
            throw new BaseException("设备名称重复，请重新输入");
        }

        ICredential auth = new BasicCredentials().withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE)
                .withAk(ak)
                .withSk(sk);

        IoTDAClient client = IoTDAClient.newBuilder().withCredential(auth)
                .withRegion(new Region(region, iotdaEndpoint))
                .build();
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        List<InitialDesired> listbodyShadow = new ArrayList<>();
        listbodyShadow.add(new InitialDesired().withServiceId("BasicService").withDesired("{}"));
        body.withShadow(listbodyShadow);
        //产品ID【productKey】
        body.withProductId(deviceDto.getProductKey());
        //设备名称【前端为昵称】
        body.withDeviceName(deviceDto.getNickname());
        //设备标识码【deviceName】
        body.withNodeId(deviceDto.getDeviceName());
        request.withBody(body);
        AddDeviceResponse response;

        //属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);

        try {
            response = client.addDevice(request);
            //设备Id赋值iotId【获取设备iotId】
            device.setIotId(response.getDeviceId());
            //ProductName【获取ProductName】
            device.setProductName(response.getProductName());
        } catch (ConnectionException e) {
            e.printStackTrace();
        }


        try {
            //保存数据
            save(device);
        } catch (Exception e) {
            //删除物联网中的设备数据
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.withDeviceId(device.getIotId());
            try {
                client.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                throw new BaseException("IOT调用，删除产品失败");
            }
            //抛出异常,同一个位置或老人不能绑定同一个产品
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }


    }

    /**
     * 查询产品列表
     *
     * @return
     */

    @Override
    public List<ProductVo> allProduct() {
        // 1. 从redis中获取数据
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);

        // 2. 判断是否存在，如不存在，返回一个空集合
        if (StringUtils.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }

        // 3. 有值，解析JSON并映射字段
        List<ProductVo> resultList = new ArrayList<>();
        try {
            // 解析JSON数组
            JsonArray jsonArray = JsonParser.parseString(jsonStr).getAsJsonArray();

            for (JsonElement element : jsonArray) {
                JsonObject jsonObject = element.getAsJsonObject();

                // 创建ProductVo对象并映射字段
                ProductVo vo = new ProductVo();
                // productId → productKey
                vo.setProductKey(jsonObject.get("productId").getAsString());
                // name → productName
                vo.setProductName(jsonObject.get("name").getAsString());

                resultList.add(vo);
            }
        } catch (Exception e) {
            // 异常处理（可选：记录日志/返回空集）
            return Collections.emptyList();
        }

        return resultList;
    }


    /**
     * 同步iot产品数据到redis
     */
    @Override
    public void syncProductList() {

        ICredential auth = new BasicCredentials()
                // 标准版/企业版需要使用衍生算法，基础版请删除配置"withDerivedPredicate";
                .withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE) // Used in derivative ak/sk authentication scenarios
                .withAk(ak)
                .withSk(sk);

        IoTDAClient client = IoTDAClient.newBuilder()
                .withCredential(auth)
                // 标准版/企业版：需自行创建Region对象，基础版：请使用IoTDARegion的region对象，如"withRegion(IoTDARegion.CN_NORTH_4)"
                .withRegion(new Region(region, iotdaEndpoint))
                .build();
        ListProductsRequest request = new ListProductsRequest();

        ListProductsResponse response;
        try {
            response = client.listProducts(request);
        } catch (Exception e) {
            throw new BaseException("IOT调用，查询产品失败");
        }

        //判断接口调通了
        if(response.getHttpStatusCode()==400){
            throw new BaseException("IOT调用失败");
        }



    //存储到redis
    redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST,JSONUtil.toJsonStr(response.getProducts()));


    }

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
    return save(device)?1:0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDevice(Device device) {

        //查询设备是否存在
        Device dbDevice = getById(device.getId());
        if(ObjectUtil.isEmpty(dbDevice)){
            throw new BaseException("设备不存在");
        }

        //先更新设备
        //如果是随身设备，物理位置设为-1
        if (device.getLocationType().equals(0)) {
            device.setPhysicalLocationType(-1);
        }

        //更新数据库中设备信息
        try {
            deviceMapper.updateDevice(device);
        } catch (Exception e) {
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }



        ICredential auth = new BasicCredentials().withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE)
                .withAk(ak)
                .withSk(sk);

        IoTDAClient client = IoTDAClient.newBuilder()
                .withCredential(auth).withRegion(new Region(region, iotdaEndpoint)).build();
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();

        body.withDeviceName(device.getNickname());
        request.withBody(body);
        UpdateDeviceResponse response;

        try {
            response = client.updateDevice(request);

        } catch (Exception e) {
            throw new BaseException("IOT调用，更新设备失败");
        }

        //判断接口调通了
        if(response.getHttpStatusCode()==400){
            throw new BaseException("IOT调用失败");
        }


        return 1;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除设备信息
     * 
     * @param device 设备主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteDeviceById(Device device) {

        //通过设备id删除设备
        remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId,device.getIotId()));


        ICredential auth = new BasicCredentials().withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE)
                .withAk(ak).withSk(sk);

        IoTDAClient client = IoTDAClient.newBuilder().withCredential(auth)
                .withRegion(new Region(region, iotdaEndpoint)).build();
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(device.getIotId());

        DeleteDeviceResponse response;


        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("IOT调用，删除设备失败");
        }


        //判断接口调通了
        if(response.getHttpStatusCode()==400){
            throw new BaseException("IOT调用失败");
        }
        return 1;


    }
}
